//
// Created by f12160c on 2018/7/26.
//

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <limits.h>

#include "leetcode/leetcode.hpp"

using namespace std;

int Solution::divide(int dividend, int divisor) {
    int flag;
    unsigned int div1;
    unsigned int div2;
    unsigned int tmp;
    unsigned int curr;

    if(dividend < 0){
        div1 = ~((unsigned int )dividend - 1);
        if(divisor < 0){
            div2 = ~((unsigned int )divisor - 1);
            flag = 1;
        }
        else{
            div2 = (unsigned int )divisor;
            flag = -1;
        }
    }
    else{
        div1 = (unsigned int )dividend;
        if(divisor < 0){
            div2 = ~((unsigned int )divisor - 1);
            flag = -1;
        }
        else{
            div2 = (unsigned int )divisor;
            flag = 1;
        }
    }

    curr = 0;
    tmp = 0;
    for(int i = 0; i < 32; i++){
        if(div1 & 0x80000000){
            curr = (curr << 1) + 1;
        }
        else {
            curr = curr << 1;
        }
        tmp = tmp << 1;
        if(curr >= div2){
            curr = curr - div2;
             tmp = tmp + 1;
        }
        div1 = div1 << 1;
    }

    if(flag == 1){
        if(tmp > (unsigned int )INT_MAX){
            tmp = (unsigned int )INT_MAX;
        }
    }
    else{
        if(tmp > ((unsigned int )INT_MAX + 1)){
            tmp = ((unsigned int )INT_MAX + 1);
        }
        tmp = ~tmp + 1;
    }
    return (int )tmp;
}
